//
//  LYRestorePool.swift
//  RxSwift_Practice
//
//  Created by 李永彬 on 2020/4/28.
//  Copyright © 2020 李永彬. All rights reserved.
//

import Foundation
import CoreBluetooth

internal class LYRestorePool: LYCBCentralManagerRestoreDelegate {
    
    var connectionPool = LYConnectionPool()
    internal var configuration: LYConfiguration?
    
    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
        guard dict.keys.contains("kCBRestoredPeripherals") else {
            return
        }
        
        let peripherals: Array<CBPeripheral> = dict[CBCentralManagerRestoredStatePeripheralsKey] as! Array

        for peripheral in peripherals {
//            let name: String = peripheral.name!
            let remotePeripheral = LYRemotePeripheral(identifier: peripheral.identifier, peripheral: peripheral)
            remotePeripheral.configuration = configuration
            delay(1.0) {
                try! self.connectionPool.connectWithTimeout(3.0, remotePeripheral: remotePeripheral) { (rePeripheral, error) in

                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: LYBluetoothConnectedFromRestoreStateNotification), object: nil, userInfo: ["peripheral" : remotePeripheral, "error": error as Any])
                }
            }
        }
    }
}
